<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>详情页面</title>
    <link rel="stylesheet" href="../css/3d.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">

    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f4f4f9;
        }

        .container {
            width: 100%;
            background: #fff;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            padding: 20px;
            border-radius: 8px;
        }

        .property {
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .property img {
            width: 500px;
            height: 350px;
            object-fit: cover;
            border-radius: 8px;
            margin-bottom: 20px;
        }

        .property h3 {
            margin: 0;
            color: #333;
        }

        .property p {
            margin: 5px 0;
            color: #666;
        }

        .price {
            color: red;
            font-size: 30px;
            font-weight: bold;
            margin-top: 20px;
        }

        .ab {
            width: 150px;
            height: 50px;
            background-color: #ffffff;
            border: none;
            box-shadow: 0px 0px 5px 2px rgba(215, 215, 216);
            margin-left: 100px;
            position: relative;
            bottom: -90px;
        }

        #reviews {
            margin-top: 20px;
            border-top: 1px solid #ddd;
            padding-top: 20px;
        }

        .review {
            border-bottom: 1px solid #ddd;
            padding: 10px 0;
        }

        .review:last-child {
            border-bottom: none;
        }

        .review h4 {
            margin: 0 0 5px;
            font-size: 1.2em;
            color: #333;
        }

        .review p {
            margin: 5px 0;
            color: #666;
        }

        .star-rating {
            display: inline-block;
            font-size: 0;
        }

        .star-rating span {
            font-size: 1.2em;
            color: gold;
            margin-right: 2px;
        }

        .review img {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            margin-right: 15px;
        }

        #p_button {
            position: relative;
            right: -500px;
            top: 10px;
            width: 100px;
            box-shadow: 0px 0px 5px 2px rgba(215, 215, 216);
            border: none;
        }

        /* 弹出表单的样式 */
        .popup-form-container {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            display: flex;
            justify-content: center;
            align-items: center;



        }

        .popup-form-content {
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            width: 350px;
            position: relative;
         top: -800px;

        }

        .close-popup-button {
            position: absolute;
            top: 10px;
            right: 10px;
            font-size: 20px;
            cursor: pointer;
        }

        .rating-container {
            display: flex;
            justify-content: space-between;
            font-size: 24px;
            margin-bottom: 15px;
        }

        .rating-star {
            cursor: pointer;
            color: #ddd; /* 默认颜色 */
        }

        .rating-star:hover,
        .rating-star.selected {
            color: #ffca28; /* 选中或悬停时的颜色 */
        }

        .comment-textarea {
            width: 100%;
            height: 80px;
            padding: 10px;
            border-radius: 5px;
            border: 1px solid #ccc;
            resize: none;
            margin-bottom: 15px;
        }

        .submit-button {
            width: 100%;
            padding: 10px;
            background-color: #28a745;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            transition: background-color 0.3s;
        }

        .submit-button:hover {
            background-color: #218838;
        }

        .comment-textarea {
            width: 90%;
            height: 80px;
            padding: 10px;
            border-radius: 5px;
            border: 1px solid #ccc;
            resize: none;
            margin-bottom: 15px;
        }

        .submit-button {
            width: 100%;
            padding: 10px;
            background-color: #28a745;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            transition: background-color 0.3s;
        }

        .submit-button:hover {
            background-color: #218838;
        }
        #bookingFormContainer {
            display: none;
            position: relative;
            top: -500px;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            /*z-index: 1000;*/
            width: 600px;

        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
        }
        .form-group input,
        .form-group textarea {
            width: 100%;
            padding: 10px;
            box-sizing: border-box;
        }
        .form-group button {
            padding: 10px 20px;
            background-color: #4CAF50;
            color: white;
            border: none;
            cursor: pointer;
            border-radius: 4px;
            transition: background-color 0.3s;
        }
        .form-group button:hover {
            background-color: #45a049;
        }
        #closeButton {
            background-color: #f44336;
            margin-right: 10px;
        }
        #closeButton:hover {
            background-color: #d32f2f;
        }

    </style>
</head>
<body >
<div style="display: flex">
    <div class="main" style="height: 550px">
        <div class="outside">
            <div class="rotas" id="rotas-container">
                <!-- 图片通过 JavaScript 动态添加 -->
            </div>
            <div class="changeBtns">
                <div class="left">&lt;</div>
                <div class="right">&gt;</div>
            </div>
        </div>
    </div>

    <div class="container">
        <div id="property-detail" class="property"></div>
        <div style="display: flex; justify-content: center; margin-top: 20px">
            <button id="follow-button" class="ab">关注房源</button>
            <button id="buy-button" class="ab">购买房源</button>
            <button id="booking-button" class="ab">预约看房</button>
        </div>
    </div>
</div>

<div style="width: 90%;box-shadow: 0px 0px 5px 2px rgba(215, 215, 216); margin-left:5%;margin-top: 20px  ">
    <div style="display: flex">
        <div style="margin-left:50%;font-size: 30px;font-weight: bold;line-height:60px;height:40px" >房子评论</div>
        <button  id="p_button">
            <img style="width: 25px;height: 25px;" src="../icon/添加.png">
            <span style="position: relative;top:-6px">发表评论</span>
        </button>
    </div>
    <div id="reviews"></div>
</div>

<!-- 隐藏的弹出表单 -->
<div id="commentForm" class="popup-form-container" style="display: none;">
    <div class="popup-form-content">
        <span class="close-popup-button" id="closeForm">&times;</span>
        <h2 style="text-align: center">发表评论</h2>
        <div style="display: flex">
            <div style="position: relative;top:5px">
                评分：
            </div>
            <div class="rating-container">
                <span class="rating-star" data-value="1">★</span>
                <span class="rating-star" data-value="2">★</span>
                <span class="rating-star" data-value="3">★</span>
                <span class="rating-star" data-value="4">★</span>
                <span class="rating-star" data-value="5">★</span>
            </div>
        </div>

        <textarea id="commentText" class="comment-textarea" placeholder="输入你的评论..." required></textarea>
<!--        <input placeholder="请输入你的昵称" id="userName" required>-->
        <button id="submitComment" class="submit-button">提交</button>
    </div>
</div>
<div id="bookingFormContainer">
    <div class="form-group">
        <label for="bookingTime">预约时间:</label>
        <input type="datetime-local" id="bookingTime">
    </div>
    <div class="form-group">
        <label for="remarkInfo">备注信息:</label>
        <textarea id="remarkInfo" rows="4"></textarea>
    </div>
    <div class="form-group">
        <button id="submitButton">提交预约</button>
        <button id="closeButton">关闭</button>
    </div>
</div>
</body>
<script src="../js/3d.js"></script>
<script>
    const token = localStorage.getItem('token'); // 从localStorage获取token

    // 选择表单按钮和关闭按钮
    const pButton = document.getElementById('p_button');
    const commentForm = document.getElementById('commentForm');
    const closeForm = document.getElementById('closeForm');
    const submitComment = document.getElementById('submitComment');
    const ratingStars = document.querySelectorAll('.rating-star');
    let selectedRating = 1; // 默认评分为1

    // 初始化，默认选中第1颗星
    function initializeRating() {
        ratingStars.forEach(star => star.classList.remove('selected'));
        ratingStars[0].classList.add('selected');
    }

    // 显示表单时，初始化星星状态
    pButton.addEventListener('click', () => {
        initializeRating();
        commentForm.style.display = 'flex';
    });

    // 关闭表单
    closeForm.addEventListener('click', () => {
        commentForm.style.display = 'none';
    });

    // 处理评分
    ratingStars.forEach(star => {
        star.addEventListener('click', () => {
            // 获取点击的星星的数值
            const value = parseInt(star.getAttribute('data-value'));

            // 移除所有星星的选中状态
            ratingStars.forEach(s => s.classList.remove('selected'));

            // 选中点击的星星及其左边所有的星星
            for (let i = 0; i < value; i++) {
                ratingStars[i].classList.add('selected');
            }

            // 设置选中的评分值
            selectedRating = value;
        });
    });


    // 页面加载时初始化
    initializeRating();
    const params = new URLSearchParams(window.location.search);
    const propertyId = params.get('propertyId');
    const amount = params.get('price');
    document.addEventListener('DOMContentLoaded', function() {
        // const params = new URLSearchParams(window.location.search);
        // const propertyId = params.get('propertyId');
        // const amount = params.get('price');
        console.log(propertyId);
        if (propertyId) {
            loadPropertyDetails(propertyId);
            loadPropertyReviews(propertyId); // 添加这行来加载评论
        } else {
            document.getElementById('property-detail').innerText = '未找到该房源信息';
        }

        // 添加“关注房源”按钮的点击事件
        const followButton = document.getElementById('follow-button');
        followButton.addEventListener('click', () => {
            followProperty(propertyId);
        });
        const buyButton = document.getElementById('buy-button');
        buyButton.addEventListener('click', () => {
            buyProperty(amount, propertyId);
        });

        function loadPropertyReviews(propertyId) {
            fetch(`http://localhost:8080/user/getReviewByPropertyId?propertyId=${propertyId}`,
                {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.code === 1) {
                        renderReviews(data.data);
                    } else {
                        document.getElementById('reviews').innerText = '未找到评论';
                    }
                })
                .catch(error => {
                    console.error('Error fetching reviews:', error);
                    document.getElementById('reviews').innerText = '获取评论时出错';
                });
        }

        function renderReviews(reviews) {
            const reviewsContainer = document.getElementById('reviews');
            reviewsContainer.innerHTML = ''; // 清空已有的评论
            reviews.forEach(review => {
                const reviewElement = document.createElement('div');
                reviewElement.classList.add('review');
                reviewElement.innerHTML = `
                <div style="display: flex;margin-left: 30px">
                <div style="margin-top: 10px">
                <img src="${review.avatar}" alt="${review.userName} 的头像">
</div>
                <div>
                <div style="display:flex">
                <div style="font-size: 20px;font-weight: bold">${review.userName}</div>
               <span style="color: #ccb104;font-size:22px;font-weight: bold;margin-left: 10px">${getStars(review.rating)}</span>

</div>

                <p>${review.comment}</p>
                <p style="font-size:0.8em;margin-top: 5px;color: #999">${new Date(review.reviewDate).toLocaleString()}</p>
</div>
</div>


            `;
                reviewsContainer.appendChild(reviewElement);
            });
        }

        // 提交表单

        // 提交按钮点击事件监听器
        submitComment.addEventListener('click', () => {
            // 获取评论文本和评分
            const commentText = document.getElementById('commentText').value;
            const userId = localStorage.getItem('userId'); // 从localStorage获取userId

            // 构建要发送的JSON数据
            const reviewData = {
                propertyId: propertyId, // 假设你从URL或其他来源获取propertyId
                userId: userId,
                rating: selectedRating, // 直接使用selectedRating变量
                comment: commentText
            };

            // 发送POST请求到后端
            fetch('http://localhost:8080/user/saveReview', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}` // 添加Authorization头部
                },
                body: JSON.stringify(reviewData) // 将数据转换为JSON字符串
            })
                .then(response => {
                    if (!response.ok) {
                        // 如果响应不是ok状态，则抛出一个错误
                        throw new Error('网络响应失败');
                    }
                    return response.json();
                })
                .then(data => {
                    // 根据后端返回的code来判断请求是否成功
                    if (data.code === 1) {
                        // 处理成功的响应
                        alert('评论提交成功：' + data.msg);
                        // 隐藏表单，重置状态
                        commentForm.style.display = 'none';
                        ratingStars.forEach(s => s.classList.remove('selected'));
                        document.getElementById('commentText').value = '';
                        selectedRating = 1; // 重置评分为1
                        initializeRating(); // 重置星星状态
                        loadPropertyReviews(propertyId);
                    } else {
                        // 处理后端返回的错误信息
                        alert('评论提交失败：' + data.msg);
                    }
                })
                .catch(error => {
                    console.error('提交评论时发生错误:', error);
                    alert('提交评论时发生错误，请稍后重试。');
                });
        });




        function getStars(rating) {
            let stars = '';
            for (let i = 0; i < 5; i++) {
                stars += i < rating ? '<span>&#9733;</span>' : '<span>&#9734;</span>';
            }
            console.log(stars);
            return stars;
        }
    });

    function loadPropertyDetails(id) {
        const url = `http://localhost:8080/user/getPropertyById?PropertyId=${id}`;

        const token = localStorage.getItem('token');

        if (!token) {
            console.error('No token found, please log in');
            return;
        }

        fetch(url, {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            }
        })
            .then(response => response.json())
            .then(data => {
                if (data.code === 1) {
                    renderPropertyDetail(data.data);
                } else {
                    document.getElementById('property-detail').innerText = '未找到该房源信息';
                }
            })
            .catch(error => console.error('Error:', error));
    }

    function renderPropertyDetail(property) {
        const rotasContainer = document.getElementById('rotas-container');
        rotasContainer.innerHTML = '';

        const images = [
            property.imageUrl,
            property.imageUrl1,
            property.imageUrl2,
            property.imageUrl3,
            property.imageUrl4,
            property.imageUrl5
        ];

        images.forEach((url, index) => {
            const imgDiv = document.createElement('div');
            const imgElement = document.createElement('img');
            imgElement.src = url;
            imgElement.alt = property.title;
            imgDiv.appendChild(imgElement);

            if (index === 0) {
                imgDiv.classList.add('sel');
            }

            rotasContainer.appendChild(imgDiv);
        });

        const propertyDetail = document.getElementById('property-detail');
        propertyDetail.innerHTML = `
                <h1 class="a">${property.description}</h1>
                <p>位置: ${property.province} ${property.city} ${property.community}</p>
                <p>类型: ${property.houseType}</p>
                <p>面积: ${property.area} 平方米</p>
                <p>每平方: ${(property.price / property.area).toFixed(2)}万 元</p>
                <p>发布时间: ${new Date(property.createTime).toLocaleString()}</p>
                <div class="price">仅需${(property.price / 10000).toFixed(2)}<span style="font-size:18px;color:#cf1919;font-weight: lighter">万</span></div>
            `;
    }

    function followProperty(propertyId) {
        const userId = localStorage.getItem('userId');
        const token = localStorage.getItem('token');

        if (!userId || !token) {
            alert('请先登录');
            return;
        }

        const url = `http://localhost:8080/user/saveFavorite?userId=${userId}&propertyId=${propertyId}`;

        fetch(url, {
            method: 'PUT',
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            }
        })
            .then(response => response.json())
            .then(data => {
                if (data.code === 1&&data.data!==0) {
                    alert('收藏成功');
                }
                else if(data.code === 1&&data.data===0){
                    alert('该房源已收藏');
                }
                else {

                    alert('收藏失败');
                }
            })
            .catch(error => console.error('Error:', error));
    }

    function buyProperty(amount,propertyId) {
        const userId = localStorage.getItem('userId');
        const token = localStorage.getItem('token');

        if (!userId || !token) {
            alert('请先登录');
            return;
        }

        const url = `http://localhost:8080/user/saveTransaction?userId=${userId}&propertyId=${propertyId}&amount=${amount}`;

        fetch(url, {
            method: 'PUT',
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            }
        })
            .then(response => response.json())
            .then(data => {
                if (data.code === 1&&data.data!==0) {
                    alert('订单提交成功');
                }
                else {

                    alert('该订单已存在');
                }
            })
            .catch(error => console.error('Error:', error));
    }

    document.getElementById('booking-button').addEventListener('click', function() {
        document.getElementById('bookingFormContainer').style.display = 'block';
    });

    document.getElementById('closeButton').addEventListener('click', function() {
        document.getElementById('bookingFormContainer').style.display = 'none';
    });

    document.getElementById('submitButton').addEventListener('click', function() {
        const bookingTime = document.getElementById('bookingTime').value;
        const remarkInfo = document.getElementById('remarkInfo').value;

        if (!bookingTime || !remarkInfo) {
            alert('请填写所有字段');
            return;
        }

        fetch(`http://localhost:8080/user/saveBooking`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            },
            body: JSON.stringify({
                propertyId: propertyId,
                userId: localStorage.getItem('userId'),
                bookingTime: bookingTime,
                remarkInfo: remarkInfo
            })
        })
            .then(response => response.json())
            .then(data => {
                if (data.code === 1) {
                    alert('预约成功');
                    document.getElementById('bookingFormContainer').style.display = 'none';
                } else {
                    alert('预约失败：' + data.msg);
                }
            })
            .catch(error => {
                console.error('Error booking property:', error);
                alert('预约失败，请稍后再试');
            });
    });
</script>
</html>
